import 'package:dio/dio.dart';
import 'package:flutter/material.dart' hide SimpleDialog;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hotpot/http/http_api.dart';
import 'package:hotpot/odoo/odoo_api.dart';
import 'package:hotpot/odoo/odoo_helper.dart';
import 'package:hotpot/route/route_ext.dart';
import 'package:hotpot/route/routes.dart';
import 'package:hotpot/utils/storage_utils.dart';
import 'package:hotpot/utils/user_utils.dart';
import 'package:hotpot/widgets/styles/text_btn.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../widgets/styles/simple_dialog.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  bool retry = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkUpdate();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: retry ? TextBtn('重试', size: 30, onTap: _retry) : const CircularProgressIndicator(),
      ),
    );
  }

  void _retry() {
    retry = false;
    setState(() {});
    login();
  }

  void login() async {
    var server = await StorageUtils.getServer();
    if (server.isEmpty) {
      Routes.loginService.pushNamed();
      return;
    }
    await OdooHelper.initClient(server);
    var list = await StorageUtils.getLogin();
    if (list.isEmpty) {
      Routes.loginData.pushNamed();
    } else {
      try {
        SmartDialog.showLoading();
        var value = await OdooHelper.init(list[0], list[1], list[2]);
        SmartDialog.dismiss();
        if (value) {
          var partner = await OdooApi.getPartner(id: OdooHelper.partnerId);
          UserUtils.init(partner.first);
          loadData();
        } else {
          retry = true;
          setState(() {});
          showToast('登录失败');
        }
      } catch (_) {
        retry = true;
        setState(() {});
        SmartDialog.dismiss();
      }
    }
  }

  void loadData() async {
    try {
      var config = await HttpApi.getPosConfigList();
      var shopList = config.result as List;
      Routes.store.popAndPushNamed(arg: {'data': shopList});
    } catch (_) {
      showToast('初始化失败');
      retry = true;
      setState(() {});
    }
  }

  void checkUpdate() async {
    HttpApi.checkUpdate().then((e) async {
      if (e['code'] == 0) {
        print(e['data']);
        var version = e['data']['buildVersion'].split('.');
        var currVersion = (await PackageInfo.fromPlatform()).version.split('.');
        var check = List.generate(currVersion.length, (i) => currVersion[i].compareTo(version[i]));
        if (check.indexWhere((e) => e < 0) != -1) {
          showDialog(
            context: context,
            builder: (_) => SimpleDialog(
              content: 'Do you need to update the application?',
              rightText: 'Yes',
              onRightTop: () {
                Routes.download.pushNamedAndPopAll(arg: {
                  'url':
                      'https://api.pgyer.com/apiv2/app/install?_api_key=64800c5a81ef22361f3d00cad87c6a0c&appKey=a50f865bca56fcfd09ab67d5425bc821'
                });
              },
              onLeftTap: () {
                login();
              },
            ),
          );
          // launchUrl(Uri.parse('https://www.pgyer.com/USkGAOx5'));
        } else {
          login();
        }
      } else {
        showToast(e['message']);
        login();
      }
    });
  }
}
